﻿using System;
using System.Collections.Generic;
using System.Globalization;
using System.Web;
using System.Web.UI;
using BusinessLogic.ClassFactory;
using DataAccess;
using Util.PageInfo;
using ValidateCommon;
using Common;
using BusinessLogic.BusinessRules;
using System.Xml;
using System.Text;
using System.Data;
using System.IO;

namespace RichECMS.ServerPages.Article
{
    public partial class Add : Article.Base.ArticleSave
    {
        public int intSectionID = -1;
        public int intCurrentSectionID;
        protected void Page_Load(object sender, EventArgs e)
        {
            Hiddenpathmain.Value = "../../news/" + State.LoginUser.VartualPath + "/Pcfiles/";
            if (!IsPostBack)
            {
                if (Request["Section"] != null)
                {
                    if (ParamAuth.IsNumber(Request["Section"].ToString()))
                    {
                        State.intSTID = int.Parse(Request["Section"].ToString());
                        intCurrentSectionID = int.Parse(Request["Section"].ToString());
                        BusinessLogic.BusinessRules.Sections.FindSectionReferRoot(State.intSTID, ref intSectionID);
                        State.intSTID = intSectionID;
                        aBack.HRef += "?Section=" + State.intSTID;
                        this.txtIssueTime.Value = DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss", DateTimeFormatInfo.InvariantInfo);
                        LitPaagePath.Text = PageInfo.ShowPagePath(State.intSTID);
                        using (SectionsFactory objFactory = new SectionsFactory())
                        {
                            BusinessLogic.BusinessRules.Sections objSections = objFactory.Creator(State.intSTID);
                            if (objSections != null)
                            {
                                DataTable tblTmp = objSections.Data.Tables[0];
                                DataRow row = tblTmp.Rows[0];
                                if (row["chvSTCName"] != DBNull.Value)
                                {
                                    LitPageName.Text = objSections.DataItem.chvSTCName;
                                    classChooser.Items.Add(objSections.DataItem.chvSTCName);
                                }
                                if (row["chvDataLabel"] != DBNull.Value)
                                {
                                    SyncDataLabel(objSections.DataItem.chvDataLabel);
                                }
                                if (row["chvDataModel"] != DBNull.Value)
                                {
                                    LitExtention.Text = ShowExtension(objSections.DataItem.chvDataModel);
                                }
                            }
                        }
                    }
                    else
                    {
                        Alert("参数错误");
                    }
                }
                else
                {
                    Alert("参数错误");
                }
            }
        }
        /// <summary>
        /// 显示自定义扩展
        /// </summary>
        /// <param name="strXml"></param>
        /// <returns></returns>
        protected string ShowExtension(string strXml)
        {
            StringBuilder objbuilder = new StringBuilder();
            try
            {
                if (!strXml.Trim().Equals(""))
                {
                    XmlDocument strXML = new XmlDocument();
                    strXML.LoadXml(strXml);
                    XmlNode objExtenRootNode = strXML.SelectSingleNode("/datamodel");
                    if (objExtenRootNode != null)
                    {
                        if (objExtenRootNode.HasChildNodes)
                        {
                            XmlNodeList objXMLNOdeList = objExtenRootNode.ChildNodes;
                            foreach (XmlNode objNodeTemp in objXMLNOdeList)
                            {
                                if (objNodeTemp.Attributes["type"] != null)
                                {
                                    string strType = objNodeTemp.Attributes["type"].Value;
                                    if (File.Exists(Server.MapPath("~/") + "ServerPages\\ExpandEditor\\" + strType + "\\template.htm"))
                                    {
                                        using (FileStream fs = new FileStream(Server.MapPath("~/") + "ServerPages\\ExpandEditor\\" + strType + "\\template.htm", FileMode.Open, FileAccess.Read, FileShare.Read))
                                        {
                                            StreamReader sr = new StreamReader(fs);
                                            string temp = sr.ReadToEnd();
                                            temp = temp.Replace("$TitlePosition$", objNodeTemp.Attributes["description"].Value).Replace("$NamePosition$", objNodeTemp.Name).Replace("$IDPosition$", objNodeTemp.Name).Replace("$CurrentValue$", "");
                                            objbuilder.Append(temp);
                                            sr.Close();
                                        }
                                    }
                                    else
                                    {
                                        Alert(string.Format("扩展配置异常:栏目{0}中的节点ID为{1}的type属性为{2}所对应的文件不存在", State.intSTID, objNodeTemp.Name, strType));
                                        return "";
                                    }
                                }
                                else
                                {
                                    Alert(string.Format("扩展配置异常:栏目{0}中的节点ID为{1}的type属性不存在", State.intSTID, objNodeTemp.Name));
                                    return "";
                                }
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Alert(ex.Message.Replace("\r\n", ""));
            }
            return objbuilder.ToString();
        }

        protected void ExpandReset()
        {
            //异常情况下恢复自定义扩展中填充的数据
            using (SectionsFactory objFactory = new SectionsFactory())
            {
                BusinessLogic.BusinessRules.Sections objSections = objFactory.Creator(State.intSTID);
                if (objSections != null)
                {
                    DataTable tblTmp = objSections.Data.Tables[0];
                    DataRow row = tblTmp.Rows[0];
                    if (row["chvDataModel"] != DBNull.Value)
                    {
                        StringBuilder objbuilder = new StringBuilder();
                        try
                        {
                            if (!row["chvDataModel"].ToString().Equals(""))
                            {
                                XmlDocument strXML = new XmlDocument();
                                strXML.LoadXml(row["chvDataModel"].ToString());
                                XmlNode objExtenRootNode = strXML.SelectSingleNode("/datamodel");
                                if (objExtenRootNode != null)
                                {
                                    if (objExtenRootNode.HasChildNodes)
                                    {
                                        XmlNodeList objXMLNOdeList = objExtenRootNode.ChildNodes;
                                        foreach (XmlNode objNodeTemp in objXMLNOdeList)
                                        {
                                            if (objNodeTemp.Attributes["type"] != null)
                                            {
                                                string strType = objNodeTemp.Attributes["type"].Value;
                                                if (File.Exists(Server.MapPath("~/") + "ServerPages\\ExpandEditor\\" + strType + "\\template.htm"))
                                                {
                                                    using (FileStream fs = new FileStream(Server.MapPath("~/") + "ServerPages\\ExpandEditor\\" + strType + "\\template.htm", FileMode.Open, FileAccess.Read, FileShare.Read))
                                                    {
                                                        StreamReader sr = new StreamReader(fs);
                                                        string temp = sr.ReadToEnd();
                                                        temp = temp.Replace("$TitlePosition$", objNodeTemp.Attributes["description"].Value).Replace("$NamePosition$", objNodeTemp.Name).Replace("$IDPosition$", objNodeTemp.Name).Replace("$CurrentValue$", Request[objNodeTemp.Name]);
                                                        objbuilder.Append(temp);
                                                        sr.Close();
                                                    }
                                                }
                                                else
                                                {
                                                    Alert(string.Format("扩展配置异常:栏目{0}中的节点ID为{1}的type属性为{2}所对应的文件不存在", State.intSTID, objNodeTemp.Name, strType));
                                                    return;
                                                }
                                            }
                                            else
                                            {
                                                Alert(string.Format("扩展配置异常:栏目{0}中的节点ID为{1}的type属性不存在", State.intSTID, objNodeTemp.Name));
                                                return;
                                            }
                                        }
                                    }
                                }
                            }
                        }
                        catch (Exception ex)
                        {
                            Alert(ex.Message.Replace("\r\n", ""));
                        }
                        LitExtention.Text = "";
                        LitExtention.Text = objbuilder.ToString();
                    }
                }
            }
        }

        /// <summary>
        /// 更新标签
        /// </summary>
        /// <param name="strXML"></param>
        private void SyncDataLabel(string strXML)
        {
            try
            {
                if (strXML.Trim() == "")
                {
                    return;
                }

                XmlDocument xmldoc = new XmlDocument();
                xmldoc.LoadXml(strXML);
                //查找标签
                XmlNode nodeLabel = xmldoc.SelectSingleNode("//infotitle");
                if (nodeLabel != null)
                {
                    if (nodeLabel.InnerXml.Trim() != "")
                    {
                        Littitle.Text = nodeLabel.InnerXml;
                    }
                }
                nodeLabel = xmldoc.SelectSingleNode("//infoclass");
                if (nodeLabel != null)
                {
                    if (nodeLabel.InnerXml.Trim() != "")
                    {
                        LitInfoClass.Text = nodeLabel.InnerXml;
                    }
                }
                nodeLabel = xmldoc.SelectSingleNode("//infosubtitle");
                if (nodeLabel != null)
                {
                    if (nodeLabel.InnerXml.Trim() != "")
                    {
                        LitSubTitle.Text = nodeLabel.InnerXml;
                    }
                }
                nodeLabel = xmldoc.SelectSingleNode("//infoArticleMan");
                if (nodeLabel != null)
                {
                    if (nodeLabel.InnerXml.Trim() != "")
                    {
                        LitInfoArticleMan.Text = nodeLabel.InnerXml;
                    }
                }
                nodeLabel = xmldoc.SelectSingleNode("//infoimage");
                if (nodeLabel != null)
                {
                    if (nodeLabel.InnerXml.Trim() != "")
                    {
                        LitInfoImage.Text = nodeLabel.InnerXml;
                    }
                }
                nodeLabel = xmldoc.SelectSingleNode("//infodescription");
                if (nodeLabel != null)
                {
                    if (nodeLabel.InnerXml.Trim() != "")
                    {
                        LitInfoDescription.Text = nodeLabel.InnerXml;
                    }
                }
                nodeLabel = xmldoc.SelectSingleNode("//infosummary");
                if (nodeLabel != null)
                {
                    if (nodeLabel.InnerXml.Trim() != "")
                    {
                        LitInfoSummary.Text = nodeLabel.InnerXml;
                    }
                }
                nodeLabel = xmldoc.SelectSingleNode("//infocontent");
                if (nodeLabel != null)
                {
                    if (nodeLabel.InnerXml.Trim() != "")
                    {
                        LitInfoContent.Text = nodeLabel.InnerXml;
                    }
                }
                nodeLabel = xmldoc.SelectSingleNode("//infosource");
                if (nodeLabel != null)
                {
                    if (nodeLabel.InnerXml.Trim() != "")
                    {
                        LiteralSource.Text = nodeLabel.InnerXml;
                    }
                }
                nodeLabel = xmldoc.SelectSingleNode("//infoauthor");
                if (nodeLabel != null)
                {
                    if (nodeLabel.InnerXml.Trim() != "")
                    {
                        LiteralAuthor.Text = nodeLabel.InnerXml;
                    }
                }
                nodeLabel = xmldoc.SelectSingleNode("//infoalltop");
                if (nodeLabel != null)
                {
                    if (nodeLabel.InnerXml.Trim() != "")
                    {
                        LiteralAllTop.Text = nodeLabel.InnerXml;
                    }
                }
                nodeLabel = xmldoc.SelectSingleNode("//infosectiontop");
                if (nodeLabel != null)
                {
                    if (nodeLabel.InnerXml.Trim() != "")
                    {
                        LiteralSectonTop.Text = nodeLabel.InnerXml;
                    }
                }
                nodeLabel = xmldoc.SelectSingleNode("//infoalltj");
                if (nodeLabel != null)
                {
                    if (nodeLabel.InnerXml.Trim() != "")
                    {
                        LiteralAllTJ.Text = nodeLabel.InnerXml;
                    }
                }
                nodeLabel = xmldoc.SelectSingleNode("//infosectiontj");
                if (nodeLabel != null)
                {
                    if (nodeLabel.InnerXml.Trim() != "")
                    {
                        LiteralSectionTJ.Text = nodeLabel.InnerXml;
                    }
                }
                nodeLabel = xmldoc.SelectSingleNode("//infoscrollnews");
                if (nodeLabel != null)
                {
                    if (nodeLabel.InnerXml.Trim() != "")
                    {
                        LiteralScrollNews.Text = nodeLabel.InnerXml;
                    }
                }
                nodeLabel = xmldoc.SelectSingleNode("//infoverify");
                if (nodeLabel != null)
                {
                    if (nodeLabel.InnerXml.Trim() != "")
                    {
                        LiteralVerify.Text = nodeLabel.InnerXml;
                    }
                }
            }
            catch (Exception ex)
            {
                Alert(ex.Message.Replace("\r\n", ""));
            }
        }

        /// <summary>
        /// 验证输入
        /// </summary>
        private bool ValidateValues()
        {
            bool bolIsValidate = true;
            if (this.txtTitle.Value.Trim().Length == 0)
            {
                Alert("请填写标题");
                bolIsValidate = false;
            }
            if (!ParamAuth.IsDateTime(SqlCommon.SqlStringFilter(this.txtIssueTime.Value)))
            {
                Alert("请输入正确的发布时间格式");
                bolIsValidate = false;
            }

            if (!ParamAuth.IsNumber(SqlCommon.SqlStringFilter(this.txtOrder.Value)))
            {
                Alert("排序请输入数字");
                bolIsValidate = false;
            }

            if (this.TextReadCount.Value.Trim() != "")
            {
                if (!ParamAuth.IsNumber(SqlCommon.SqlStringFilter(this.TextReadCount.Value.Trim())))
                {
                    Alert("阅读次数请输入数字");
                    bolIsValidate = false;
                }
            }

            return bolIsValidate;
        }

        /// <summary>
        /// 提交数据
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void SubmitBtnHander(object sender, ImageClickEventArgs e)
        {
            intCurrentSectionID = int.Parse(Request["Section"].ToString());
            bool bolIssueResult = false;
            if (!ValidateValues())
            {
                ExpandReset();
                return;
            }

            using (DBManager objDBManager = new DBManager())
            {
                objDBManager.BeginTransaction();
                try
                {
                    SectionsFactory objSectionsFactory = new SectionsFactory(objDBManager);
                    BusinessLogic.BusinessRules.Sections objSections = objSectionsFactory.Creator(State.intSTID);
                    if (objSections != null)
                    {
                        if (!objSections.DataItem.IsintStateReferNull())
                        {
                            if (objSections.DataItem.intStateRefer == (int)Common.Utility.StateRefer.Yes)
                            {
                                if (objSections.DataItem.IsintReferSectionIDNull())
                                {
                                    Alert("该文章所属栏目设置了引用状态，但没有正确设置引用栏目，请检查");
                                    objSectionsFactory.Dispose();
                                    objDBManager.Dispose();
                                    return;
                                }
                            }
                        }
                    }
                    else
                    {
                        Alert("该文章所属栏目不存在，请检查");
                        objSectionsFactory.Dispose();
                        objDBManager.Dispose();
                        return;
                    }

                    ArticleFactory objFactory = new ArticleFactory(objDBManager);
                    BusinessLogic.BusinessRules.Article objArticle = objFactory.NewInstance();
                    //插入文章表
                    objArticle.DataItem.chvKeyWords = this.txtkeyWord1.Value + "," + this.txtkeyWord2.Value + "," + this.txtkeyWord3.Value + "," + this.txtkeyWord4.Value;
                    objArticle.DataItem.chvSummary = this.txtSummary.Value.Replace("\"/news/" + State.LoginUser.VartualPath + "/Pcfiles/", "\"../Pcfiles/");
                    if (Imghidden.Value.Length != 0)
                    {
                        objArticle.DataItem.chvMainMiniPic = Imghidden.Value;
                        string strOlnyName = Imghidden.Value.Remove(Imghidden.Value.LastIndexOf('.'));
                        string strExtensionName = Imghidden.Value.Remove(0, Imghidden.Value.LastIndexOf('.'));
                        objArticle.DataItem.chvMainPic = Imghidden.Value.Replace("mini", "");
                    }
                    else
                    {
                        objArticle.DataItem.chvMainPic = "default.jpg";
                        objArticle.DataItem.chvMainMiniPic = "default.jpg"; ;
                    }
                    objArticle.DataItem.txtContent = this.txtContent.Value.Replace("\"/news/" + State.LoginUser.VartualPath + "/Pcfiles/", "\"../Pcfiles/");
                    objArticle.DataItem.dtmInTime = Convert.ToDateTime(this.txtIssueTime.Value);
                    objArticle.DataItem.chvTitle = this.txtTitle.Value;
                    objArticle.DataItem.chvSubTitle = this.txtSecondTitle.Value;
                    objArticle.DataItem.chvArticleInMan = this.txtAuthor.Value;
                    var inttxtdescriptionLength = this.txtdescription.Value.Length;
                    var intArticleDescriptionMaxLength = AppConfig.GetArticleDescriptionMaxLength();
                    if (inttxtdescriptionLength > intArticleDescriptionMaxLength)
                    {
                        objArticle.DataItem.chvDescription = this.txtdescription.Value.Remove(intArticleDescriptionMaxLength);
                    }
                    else
                    {
                        objArticle.DataItem.chvDescription = this.txtdescription.Value;
                    }
                    objArticle.DataItem.chvRedirectUrl = this.TextRedirectUrl.Value.Trim();
                    objArticle.DataItem.chvVedioPath = this.txtvedio.Value;
                    objArticle.DataItem.chvFilePath = this.txtfile.Value;
                    objArticle.DataItem.chvArticleSource = this.TextSource.Value;
                    objArticle.DataItem.chvAuthor = this.TextAuthor.Value;
                    objArticle.DataItem.txtSeoTitle = this.txtseotitle.Value.Trim().Length == 0 ? "" : this.txtseotitle.Value;
                    objArticle.DataItem.txtSeoKeywords = this.txtseokeywords.Value.Trim().Length == 0 ? "" : this.txtseokeywords.Value;
                    objArticle.DataItem.txtSeodescription = this.txtseodescription.Value.Trim().Length == 0 ? "" : this.txtseodescription.Value;
                    objArticle.DataItem.dtmIssueTime = Convert.ToDateTime(DateTime.Now.ToString("yy/MM/dd HH:mm"));
                    objArticle.DataItem.intRecycling = (int)Utility.ArticleState.NoRecycling;
                    objArticle.DataItem.intWSID = State.intWSID;

                    if (objSections != null)
                    {
                        DataTable tblTmp = objSections.Data.Tables[0];
                        DataRow row = tblTmp.Rows[0];
                        if (row["chvDataModel"] != DBNull.Value)
                        {
                            StringBuilder objbuilder = new StringBuilder();
                            try
                            {
                                if (!objSections.DataItem.chvDataModel.Equals(""))
                                {
                                    XmlDocument strXML = new XmlDocument();
                                    strXML.LoadXml(objSections.DataItem.chvDataModel);
                                    XmlNode objExtenRootNode = strXML.SelectSingleNode("/datamodel");
                                    if (objExtenRootNode != null)
                                    {
                                        if (objExtenRootNode.HasChildNodes)
                                        {
                                            XmlNodeList objXMLNOdeList = objExtenRootNode.ChildNodes;
                                            foreach (XmlNode objNodeTemp in objXMLNOdeList)
                                            {

                                                if (Request[objNodeTemp.Name] != null)
                                                {
                                                    string strFormValue = Request[objNodeTemp.Name];
                                                    XmlCDataSection objXmlCDataSection = strXML.CreateCDataSection(strFormValue);
                                                    objNodeTemp.AppendChild(objXmlCDataSection);
                                                }
                                            }
                                        }
                                    }
                                    objArticle.DataItem.txtExpand = strXML.OuterXml;
                                }
                            }
                            catch (Exception ex)
                            {
                                Alert(ex.Message.Replace("\r\n", ""));
                                return;
                            }
                        }
                    }

                    objArticle.Insert();

                    //关联表
                    objSections = objSectionsFactory.CreatorBySql(" intSectionID=" + State.intSTID);
                    ArtSecRelationFactory objAsFactory = new ArtSecRelationFactory(objDBManager);
                    BusinessLogic.BusinessRules.ArtSecRelation objArtSecRelation = objAsFactory.NewInstance();
                    if (objSections != null)
                    {
                        objArtSecRelation.DataItem.intSectionID = objSections.DataItem.intSectionID;
                        objArtSecRelation.DataItem.intArticleID = objArticle.DataItem.intArticleID;
                        //获取默认阅读数
                        string strdefaultreadcount = System.Configuration.ConfigurationSettings.AppSettings["DefaultReadCount"] ?? (ParamAuth.IsNumber(this.TextReadCount.Value.Trim()) ? this.TextReadCount.Value.Trim() : "0");
                        objArtSecRelation.DataItem.intAccessCount = ParamAuth.IsNumber(strdefaultreadcount) ? Convert.ToInt32(strdefaultreadcount) : 0;
                        objArtSecRelation.DataItem.intSort = int.Parse(this.txtOrder.Value);
                        objArtSecRelation.DataItem.dtmIssueTime = Convert.ToDateTime(DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss", DateTimeFormatInfo.InvariantInfo));
                        objArtSecRelation.DataItem.blnIssue = (int)Utility.ArticleState.NoIssue;
                        objArtSecRelation.DataItem.blnRefers = (int)Utility.ArticleRefersState.NoRefers;
                        objArtSecRelation.DataItem.intState = (int)Utility.ArticleState.NoIssue;
                        objArtSecRelation.DataItem.intType = (int)Utility.ArticleType.Article;
                        objArtSecRelation.DataItem.intWSID = State.intWSID;
                        //文章位置状态
                        objArtSecRelation.DataItem.intVerify = CkboxPublish.Checked == true ? 1 : 0;
                        objArtSecRelation.DataItem.intGlobalRec = CkboxIsGlobalRec.Checked == true ? 1 : 0;
                        objArtSecRelation.DataItem.intSectionRec = CkboxIsPartRec.Checked == true ? 1 : 0;
                        objArtSecRelation.DataItem.intGlobalTop = CkboxIsGlobalTop.Checked == true ? 1 : 0;
                        objArtSecRelation.DataItem.intSectionTop = CkboxIsPartTop.Checked == true ? 1 : 0;
                        objArtSecRelation.DataItem.intScroll = CkboxIsScroll.Checked == true ? 1 : 0;
                        objArtSecRelation.Insert();
                    }

                    objSections = objSectionsFactory.CreatorBySql(" intSectionID=" + State.intSTID + " or intReferSectionID=" + State.intSTID);
                    SectionsFactory objSFactory = new SectionsFactory(objDBManager);

                    if (objSections != null)
                    {
                        BusinessLogic.BusinessRules.Sections objSectionsmain = objSFactory.CreatorBySql(" intParentId=0 ");
                        if (objSectionsmain != null)
                        {
                            for (int i = 0; i < objSectionsmain.Count; i++)
                            {
                                objSectionsmain.DataItem.intIssueState = (int)Utility.STIssueState.NoIssue;
                                objSectionsmain.SelectRow(i + 1);
                            }
                            objSectionsmain.Update();
                        }
                        //提交
                        objDBManager.Commit();

                        for (int i = 0; i < objSections.Count; i++)
                        {
                            //重置栏目相关均为未发布状态
                            FindparentSection(objSections.DataItem.intSectionID);
                            bolIssueResult = CreateSavePage(State.intWSID, objArtSecRelation.DataItem.intSecArtID, objSections.DataItem.intSectionID);
                            objSections.SelectRow(i + 1);
                        }
                    }

                    AlertAndRedirect("修改成功" + (bolIssueResult == true ? ",已经自动发布该文章页" : "") + "！", "../Section/List.aspx?Section=" + Request["Section"].ToString(), false);
                }
                catch (Exception ex)
                {
                    Alert(ex.Message.ToString().Replace("\r\n", " "));
                    objDBManager.Rollback();
                    objDBManager.Dispose();
                    ExpandReset();
                }
                finally
                {
                    objDBManager.Dispose();
                }
            }
        }

        private void FindparentSection(int intSectionId)
        {
            using (SectionsFactory objSFactory = new SectionsFactory())
            {
                BusinessLogic.BusinessRules.Sections objSections = objSFactory.Creator(intSectionId);
                if (objSections != null)
                {
                    objSections.DataItem.intIssueState = (int)Utility.STIssueState.NoIssue;
                    objSections.Update();
                    objSections = objSFactory.CreatorBySql(" intParentId=" + objSections.DataItem.intParentID + " ");
                    if (objSections != null)
                    {
                        objSections.DataItem.intIssueState = (int)Utility.STIssueState.NoIssue;
                        objSections.Update();
                        FindparentSection(objSections.DataItem.intParentID);
                    }
                }
            }
        }
    }
}